import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:music_app/api/mock_api.dart';
import 'package:music_app/controllers/audio_player_controller.dart';
import 'package:music_app/widget/song_item.dart';

class RecommentSongs extends StatefulWidget {
  const RecommentSongs({super.key});

  @override
  State<RecommentSongs> createState() => _RecommentSongsState();
}

class _RecommentSongsState extends State<RecommentSongs> {
  // 音乐播放控制方法
  final audioController = Get.find<AudioPlayerController>();
  // 数据列表
  List<dynamic> _songs = [];

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      getData();
    });
  }

  Future<void> getData() async {
    try {
      final response = await MockApi.fetchRecommendSongs();
      final List<dynamic> songs = response['data']['dailySongs'];
      setState(() {
        _songs = songs.take(9).toList(); // 只取前 9 条
      });
    } catch (e) {
      setState(() {
        _songs = []; // 只取前 9 条
      });
    } finally {}
  }

  @override
  Widget build(BuildContext context) {
    debugPrint('recomment_songs-build');
    double width = MediaQuery.of(context).size.width - 50;
    double height = 64 * 3 + 24; // 每个SongItem组件高度是 64 再加上 24的底部边距
    List<List<dynamic>> chunks = [];
    for (var i = 0; i < _songs.length; i += 3) {
      chunks.add(
        _songs.sublist(i, i + 3 > _songs.length ? _songs.length : i + 3),
      );
    }
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Text(
          '根据你喜爱的歌曲推荐',
          style: TextStyle(
            fontSize: 18,
            fontWeight: FontWeight.bold,
            color: Colors.black,
          ),
        ),
        const SizedBox(height: 8),
        SizedBox(
          height: height,
          child: ListView.builder(
            scrollDirection: Axis.horizontal,
            itemCount: chunks.length,
            itemBuilder: (context, index) {
              return SizedBox(
                width: width,
                child: Column(
                  children: chunks[index].map(
                    (song) {
                      return SongItem(
                        imageUrl: song['al']['picUrl'],
                        title: song['name'],
                        artist: (song['ar'] as List)
                            .map(
                              (artist) => artist['name'],
                            )
                            .join(', '),
                        onTap: () {
                          audioController.playSong(song);
                          // 你可以在这里实现点击事件
                        },
                      );
                    },
                  ).toList(),
                ),
              );
            },
          ),
        )
      ],
    );
  }
}
